package br.sales.view.bean;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import br.sales.controller.INewsletterControler;
import br.sales.controller.NewsletterControlerImpl;
import br.sales.entity.Newsletter;
import br.sales.entity.exception.EntityExistsException;
import br.sales.persistence.exception.DBContainerNotInitializedException;
import br.sales.view.util.ViewUtil;

@RequestScoped
@ManagedBean(name="newsletterRequestBean")
public class NewsletterRequestBean implements Serializable{

	private static final long serialVersionUID = 1L;
	private Newsletter newsletter;
	private String email;
	
	public NewsletterRequestBean() {
	}
	
	public void create(){
		try {
			newsletter = new Newsletter();
			newsletter.setEmail(email);
			newsletter.setActive(true);
			NewsletterControlerImpl.getInstance().create(newsletter);
			ViewUtil.addMessage(FacesContext.getCurrentInstance(),"form_newsletter:input_text_newsletter_email",ViewUtil.getResourceBundle(FacesContext.getCurrentInstance(),"newsletter_created_success"), FacesMessage.SEVERITY_INFO);
			email = null;
		} catch (DBContainerNotInitializedException e) {
			ViewUtil.addMessage(FacesContext.getCurrentInstance(),ViewUtil.getResourceBundle(FacesContext.getCurrentInstance(),"database_error"), FacesMessage.SEVERITY_FATAL);
			return;
		}  catch (EntityExistsException e) {
			ViewUtil.addMessage(FacesContext.getCurrentInstance(),"form_newsletter:input_text_newsletter_email",ViewUtil.getResourceBundle(FacesContext.getCurrentInstance(),"email_in_use"), FacesMessage.SEVERITY_ERROR);
			return;
		}
	}

	public Newsletter getNewsletter() {
		return newsletter;
	}

	public void setNewsletter(Newsletter newsletter) {
		this.newsletter = newsletter;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}
	
	
	
}
